package com.tmsps.ne4weixin.bean.message.send;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.tmsps.ne4weixin.annotation.XStreamCDATA;
import com.tmsps.ne4weixin.annotation.XStreamFactory;
import com.tmsps.ne4weixin.bean.message.event.BaseEvent;
import com.tmsps.ne4weixin.bean.message.receive.InBaseMessage;
import com.tmsps.ne4weixin.config.enumeration.MsgTypeEnum;

import lombok.Data;

/**
 * @Title: BaseMessage.java
 * @Package: com.tmsps.ne4weixin.bean.send
 * @Description: 被动回复用户消息BaseMessage
 */
@Data
public class OutBaseMessage {

	/**
	 * 必填 是 接收方帐号（收到的OpenID）
	 */
	@XStreamCDATA
	@XStreamAlias("ToUserName")
	private String toUserName;

	/**
	 * 必填 是 发送方帐号（一个OpenID）
	 */
	@XStreamCDATA
	@XStreamAlias("FromUserName")
	private String fromUserName;

	/**
	 * 必填 是 消息创建时间 （整型）
	 */
	@XStreamAlias("CreateTime")
	private String createTime;

	/**
	 * 必填 是 消息类型
	 */
	@XStreamCDATA
	@XStreamAlias("MsgType")
	protected String msgType;

	public OutBaseMessage(MsgTypeEnum msgType) {
		this.msgType = msgType.toName();
		this.createTime = now();
	}

	public OutBaseMessage(MsgTypeEnum msgType, String toUserName, String fromUserName) {
		this(msgType);
		this.toUserName = toUserName;
		this.fromUserName = fromUserName;
		this.createTime = now();
	}

	public OutBaseMessage(MsgTypeEnum msgType, String toUserName, String fromUserName, String createTime) {
		this(msgType);
		this.toUserName = toUserName;
		this.fromUserName = fromUserName;
		this.createTime = createTime;
	}

	/**
	 * 从接收到的消息构造要发送的消息
	 */
	public OutBaseMessage(InBaseMessage iBMessage,MsgTypeEnum msgType) {
		this(msgType);
		this.toUserName = iBMessage.getFromUserName();
		this.fromUserName = iBMessage.getToUserName();
		this.createTime = now();
	}

	/**
	 * 从接收到的事件构造要发送的消息
	 */
	public OutBaseMessage(BaseEvent event,MsgTypeEnum msgType) {
		this(msgType);
		this.toUserName = event.getFromUserName();
		this.fromUserName = event.getToUserName();
		this.createTime = now();
	}

	// createTime
	public String now() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}

	public String toXML() {
		XStream xStream = XStreamFactory.getXStream();
		xStream.autodetectAnnotations(true);
		xStream.aliasSystemAttribute(null, "class");
		return xStream.toXML(this);
	}
}
